<template>
  <el-dialog v-model="visible" :title="!dataForm.id ? '新增' : '修改'" :close-on-click-modal="false">
    <el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="105px" @keyup.enter="submitHandle()">
      <div class="item_line">
        <el-form-item prop="sysOrgId" label="所属公司">
          <ma-org-select v-model="dataForm.sysOrgId" placeholder="请选择"></ma-org-select>
        </el-form-item>
        <el-form-item label="车编号" prop="serialNo">
          <el-input v-model="dataForm.serialNo" placeholder="车编号"></el-input>
        </el-form-item>
      </div>
      <div class="item_line">
        <el-form-item label="绑定设备imei" prop="imei">
          <el-select v-model="dataForm.imei" filterable allow-create remote :remote-method="remoteMethod" :loading="inputLoading" placeholder="请选择">
            <el-option v-for="item in imeiList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定司机" prop="driverId">
          <el-select v-model="dataForm.driverId" placeholder="请选择">
            <el-option v-for="item in driverList" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
      </div>
      <div class="item_line">
        <el-form-item label="车牌号" prop="plateNo">
          <el-input v-model="dataForm.plateNo" placeholder="车牌号"></el-input>
        </el-form-item>
        <el-form-item label="车品牌" prop="brandName">
          <el-input v-model="dataForm.brandName" placeholder="车品牌"></el-input>
        </el-form-item>
      </div>
      <div class="item_line">
        <el-form-item label="VIN号" prop="vinNo">
          <el-input v-model="dataForm.vinNo" placeholder="VIN号"></el-input>
        </el-form-item>
        <el-form-item label="发动机号" prop="engineNo">
          <el-input v-model="dataForm.engineNo" placeholder="发动机号"></el-input>
        </el-form-item>
      </div>
      <div class="item_line">
        <el-form-item label="车挂类型" prop="vehicleType">
          <ma-dict-select v-model="dataForm.vehicleType" placeholder="请选择" dict-type="vehicle_type" style="width: 100%"></ma-dict-select>
        </el-form-item>
        <el-form-item label="车辆类型" prop="carType">
          <ma-dict-select v-model="dataForm.carType" placeholder="请选择" dict-type="car_type" style="width: 100%"></ma-dict-select>
        </el-form-item>
      </div>
      <div class="item_line">
        <el-form-item label="燃料类型" prop="fuelType">
          <ma-dict-select v-model="dataForm.fuelType" placeholder="请选择" dict-type="fuel_type" style="width: 100%"></ma-dict-select>
        </el-form-item>
        <el-form-item label="运输煤种" prop="coalType">
          <ma-dict-select v-model="dataForm.coalType" placeholder="请选择" dict-type="coal_type" style="width: 100%"></ma-dict-select>
        </el-form-item>
      </div>
      <div class="item_line">
        <el-form-item label="排放标准" prop="emissionStandards">
          <ma-dict-select v-model="dataForm.emissionStandards" placeholder="请选择" dict-type="emission_standards" style="width: 100%"></ma-dict-select>
        </el-form-item>
        <div></div>
      </div>
      <el-form-item label="行驶证照片" prop="licensePhoto">
        <el-upload
          class="avatar-uploader"
          :action="constant.uploadUrl"
          :headers="{
            Authorization: userStore.token
          }"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="dataForm.licensePhoto" :src="dataForm.licensePhoto" class="avatar" alt="" />
          <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="submitHandle()">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import { useCarApi, useCarSubmitApi } from '@/api/biz/car'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { UploadProps } from 'element-plus'
import { useAppStore } from '@/store/modules/app'
import constant from '@/utils/constant'
import { useUserStore } from '@/store/modules/user'
import { useDriverListApi } from '@/api/biz/driver'
import { useSearchImeiApi } from '@/api/gps/device'

const inputLoading = ref(false)
const emit = defineEmits(['refreshDataList'])
const appStore = useAppStore()
const userStore = useUserStore()
const visible = ref(false)
const dataFormRef = ref()
const driverList = ref<any[]>([])
const imeiList = ref<any[]>([])
const dataForm = reactive({
  id: '',
  serialNo: '',
  plateNo: '',
  brandName: '',
  vehicleType: '',
  carType: '',
  vinNo: '',
  engineNo: '',
  fuelType: '',
  coalType: '',
  emissionStandards: '',
  licensePhoto: '',
  imei: '',
  driverId: '',
  sysOrgId: '',
})

const init = (id?: number, orgId?: string) => {
  console.log(id)
  visible.value = true
  dataForm.id = ''

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields()
  }

  if (id) {
    getCar(id)
  } else {
    // console.log(orgId)
    dataForm.sysOrgId = orgId!
  }
  getDriverList()
  // getImeiList()
}

const getCar = (id: number) => {
  useCarApi(id).then((res) => {
    Object.assign(dataForm, res.data)
    console.log(dataForm)
  })
}

const dataRules = ref({
  plateNo: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  serialNo: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  sysOrgId: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
  imei: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
})

function remoteMethod(query: string) {
  if (query) {
    inputLoading.value = true
    useSearchImeiApi(query).then((res) => {
      inputLoading.value = false
      imeiList.value = res.data
    })
  } else {
    imeiList.value = []
  }
}

function firmChange(e){
  console.log(132)
}

function getDriverList() {
  useDriverListApi().then((res) => {
    driverList.value = res.data
  })
}
function getImeiList() {
  useImeiListApi().then((res) => {
    imeiList.value = res.data
  })
}

const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
  dataForm.licensePhoto = URL.createObjectURL(uploadFile.raw!)
}

const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}

// 表单提交
const submitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false
    }
    useCarSubmitApi(dataForm).then(() => {
      ElMessage.success({
        message: '操作成功',
        duration: 500,
        onClose: () => {
          visible.value = false
          emit('refreshDataList')
        }
      })
    })
  })
}

defineExpose({
  init
})
</script>

<style scoped>
.item_line {
  display: flex;
}
.item_line > div {
  flex: 1;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
